package com.abel.demo.util;

import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class CryptoUtil {
    private static final String AES_ALGORITHM = "AES/CBC/PKCS5Padding";

    private static Cipher getCipher(String key, int model, String ivKey) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes("utf-8"), "AES");
        IvParameterSpec iv = new IvParameterSpec(ivKey.getBytes("utf-8"));//使用CBC模式，需要一个向量iv，可增加加密算法的强度

        Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
        cipher.init(model, secretKeySpec, iv);
        return cipher;
    }

    // AES-128-CBC加密
    public static String encAES(byte[] data, String key, String ivKey) throws Exception {
        Cipher cipher = getCipher(key, Cipher.ENCRYPT_MODE, ivKey);
        return Base64.encodeBase64String(cipher.doFinal(data));
    }

    // AES-128-CBC解密
    public static String decAES(byte[] data, String key, String ivKey) throws Exception {
        Cipher cipher = getCipher(key, Cipher.DECRYPT_MODE, ivKey);
        byte[] decBytes = cipher.doFinal(Base64.decodeBase64(data));
        return new String(decBytes);
    }
}
